#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import os
import sys
import web
import json

from Umpweb.db import  api as db_api
from Umpweb.common import utils
from Umpweb.base import session, _, render_jinja


reload(sys)
sys.setdefaultencoding('utf-8')


urls = ( 
    '/list',         'TaskList',
    '/grid',         'GridTask',
    '/detail',       'TaskDetail',
    '/get',          'TaskGet',
)

app = web.application(urls, locals())
render = render_jinja('static/templates/task', encoding='utf-8',)


class TaskList:
    def GET(self):
        return render.task_list()

class TaskDetail:
    def GET(self):
        x = web.input()
        task = db_api.task_get(x.get('task_id'))
        return render.task_detail(task=task)

class GridTask:

    def GET(self):
        web_input = web.input()
        page, total, records, rows = \
                utils.grid_rows_query(db_api.task_table, web_input, filters={})

        cells = ['id', 'name', 'target', 'status', 'detail', 'created_at', 'finished_at']
        rows_json = utils.grid_json(page, total, records, rows, 'id', cells)
        web.header("Content-Type", "application/json")
        return rows_json


class TaskGet:

    def GET(self):
        web.header("Content-Type", "application/json")
        web_input = web.input()
        if web_input['task'] == 'processing':
            tasks = db_api.task_get_with_status('processing')
        if web_input['task'] == 'recent':
            tasks = db_api.task_get_recent(limit=10)
        
        return json.dumps(tasks)
        
